package com.yunchang.springboot.scheduled.amazonAdvert;

import com.yunchang.springboot.mapper.shop.AreaMapper;
import com.yunchang.springboot.mapper.shop.ProfileMapper;
import com.yunchang.springboot.mapper.shop.ShopAreaMapper;
import com.yunchang.springboot.mapper.shop.ShopMapper;
import com.yunchang.springboot.mapper.sqlTable.SqlTableMapper;
import com.yunchang.springboot.models.Area;
import com.yunchang.springboot.models.DO.ShopAreaProfile;
import com.yunchang.springboot.models.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
@Component
public class AmazonAdvErrorDateSchedule {
    @Autowired
    SqlTableMapper sqlTableMapper;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    ShopAreaMapper shopAreaMapper;
    @Autowired
    ProfileMapper profileMapper;
    @Autowired
    AreaMapper areaMapper;

    private static String[] TABLE_NAME = {"original_data_adv_productads_report", "original_data_adv_campaigns_report", "original_data_adv_adgroups_report",
            "original_data_adv_targets_report", "original_data_adv_keywords_report", "original_data_adv_asins_report","amazon_adv_brands_campaign_report",
            "amazon_adv_brands_ad_groups_report", "amazon_adv_brands_keyword_report", "amazon_adv_brands_target_report", "amazon_adv_brands_search_term_report"};

    @Scheduled(cron = "00 50 23 ? * *")
    public void addErrorDate() {
        log.info("每日更新广告接口的error_date表任务开始");
        try {
            List<ShopAreaProfile> shopAreaProfiles = profileMapper.getAllDatas();
            for (ShopAreaProfile shopAreaProfile : shopAreaProfiles) {
                Area area = areaMapper.getOneInfoByAreaId(shopAreaProfile.getAreaId());
                Shop shop = shopMapper.getOneInfoByShopId(shopAreaProfile.getShopId());
                String sellerId = shop.getSellerId();
                String areaCode = area.getAdvertCountryCode();
                IN:
                for (int i = 0; i < TABLE_NAME.length-6; i++) {
                    if ("EU".equals(areaCode)) {
                        break IN;
                    }
                    //遍历插入
                    sqlTableMapper.insertErrorDate(sellerId, areaCode, TABLE_NAME[i], (i + 1));
                }
            }
        } catch (Exception e) {
            log.error("每日更新广告接口的error_date表任务失败，详情：" + e.getMessage());
        }
        log.info("每日更新广告接口的error_date表任务结束");
    }
}
